import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:day03_flutter/components/search_box.dart';
import 'package:carousel_slider/carousel_slider.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final Dio _dio = Dio();
  Map<String, dynamic>? _pageData;
  List<dynamic> _bannerList = [];
  List<dynamic> _navList = []; // 添加导航列表数据
  List<dynamic> _goodsList = []; // 添加商品列表数据

  @override
  void initState() {
    super.initState();
    _fetchHomeData();
  }

  Future<void> _fetchHomeData() async {
    try {
      final response = await _dio.get(
        'https://smart-shop.itheima.net/index.php',
        queryParameters: {'s': '/api/page/detail'},
      );

      setState(() {
        _pageData = response.data;
        final items = response.data['data']['pageData']['items'] as List;
        
        // 获取轮播图数据
        final bannerItem = items.firstWhere((item) => item['type'] == 'banner');
        _bannerList = bannerItem['data'];
        
        // 获取导航数据
        final navItem = items.firstWhere((item) => item['type'] == 'navBar');
        _navList = navItem['data'];
        
        // 获取商品数据
        final goodsItem = items.firstWhere((item) => item['type'] == 'goods');
        _goodsList = goodsItem['data'];
      });
    } catch (e) {
      debugPrint('获取数据失败: $e');
    }
  }

  // 构建导航区域
  Widget _buildNavigation() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      color: Colors.white,
      child: Wrap(
        alignment: WrapAlignment.spaceAround,
        spacing: 10,  // 水平间距
        runSpacing: 20,  // 垂直间距
        children: _navList.map((item) {
          return SizedBox(
            width: MediaQuery.of(context).size.width / 5 - 10,
            child: _buildNavItem(item),
          );
        }).toList(),
      ),
    );
  }

  // 构建单个导航项
  Widget _buildNavItem(Map<String, dynamic> item) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Image.network(
          item['imgUrl'],
          width: 45,
          height: 45,
          fit: BoxFit.cover,
        ),
        const SizedBox(height: 5),
        Text(
          item['text'],
          style: const TextStyle(
            fontSize: 12,
            color: Color(0xFF333333),
          ),
          textAlign: TextAlign.center,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  // 构建轮播图组件
  Widget _buildBanner() {
    if (_bannerList.isEmpty) {
      return const SizedBox();
    }

    return CarouselSlider(
      options: CarouselOptions(
        height: 300,
        aspectRatio: 16 / 9,
        viewportFraction: 1,
        initialPage: 0,
        enableInfiniteScroll: true,
        reverse: false,
        autoPlay: true,
        autoPlayInterval: const Duration(seconds: 3),
        autoPlayAnimationDuration: const Duration(milliseconds: 800),
        autoPlayCurve: Curves.fastOutSlowIn,
        enlargeCenterPage: false,
        scrollDirection: Axis.horizontal,
      ),
      items: _bannerList.map((item) {
        return Builder(
          builder: (BuildContext context) {
            return Container(
              width: MediaQuery.of(context).size.width,
              margin: const EdgeInsets.symmetric(horizontal: 0),
              child: Image.network(
                item['imgUrl'],
                fit: BoxFit.cover,
              ),
            );
          },
        );
      }).toList(),
    );
  }

  // 构建图片区域
  Widget _buildImageSection() {
    if (_pageData == null) return const SizedBox();
    
    final items = _pageData!['data']['pageData']['items'] as List;
    final imageItem = items.firstWhere((item) => item['type'] == 'image', orElse: () => null);
    
    if (imageItem == null) return const SizedBox();
    
    return Container(
      margin: const EdgeInsets.only(top: 10),
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Image.network(
        imageItem['data'][0]['imgUrl'],
        fit: BoxFit.cover,
        width: double.infinity,
      ),
    );
  }

  // 构建猜你喜欢标题
  Widget _buildGuessYouLike() {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '—— 猜你喜欢 ——',
        style: TextStyle(
          fontSize: 16,
          color: Color(0xFF333333),
        ),
      ),
    );
  }

  // 构建商品列表
  Widget _buildGoodsList() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _goodsList.length,
        itemBuilder: (context, index) {
          final item = _goodsList[index];
          return Container(
            margin: const EdgeInsets.only(bottom: 10),
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 商品图片
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: Image.network(
                    item['goods_image'],
                    width: 120,
                    height: 120,
                    fit: BoxFit.cover,
                  ),
                ),
                const SizedBox(width: 10),
                // 商品信息
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 商品名称
                      Text(
                        item['goods_name'],
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(
                          fontSize: 14,
                          height: 1.2,
                        ),
                      ),
                      const SizedBox(height: 8),
                      // 销量
                      Text(
                        '已售${item['goods_sales']}件',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.grey,
                        ),
                      ),
                      const SizedBox(height: 8),
                      // 价格区域
                      Row(
                        children: [
                          Text(
                            '¥${item['goods_price_min']}',
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.red,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(width: 8),
                          if (item['line_price_min'] != '0.00')
                            Text(
                              '¥${item['line_price_min']}',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Colors.grey,
                                decoration: TextDecoration.lineThrough,
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F5F5),
      appBar: AppBar(
        title: const Text(
          '智慧商城',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        backgroundColor: Colors.red,
        elevation: 0,
      ),
      body: _pageData == null
          ? const Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              child: Column(
                children: [
                  Container(
                    padding: const EdgeInsets.fromLTRB(15, 10, 15, 10),
                    color: Colors.red,
                    child: SearchBox(
                      onTap: () {
                        debugPrint('搜索被点击');
                      },
                    ),
                  ),
                  // 轮播图
                  _buildBanner(),
                  // 导航区域
                  _buildNavigation(),
                  // 图片区域
                  _buildImageSection(),
                  // 猜你喜欢
                  _buildGuessYouLike(),
                  // 添加商品列表
                  _buildGoodsList(),
                ],
              ),
            ),
    );
  }
}
